package com.yisu.expressway.utils;

import android.util.Log;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;

import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.yisu.expressway.BuildConfig;
import com.yisu.expressway.driver_revelation.model.TopicListItem;
import com.yisu.expressway.login.LoginManager;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by matteo on 2016/2/2.
 */
public class QiniuUploadManager {

    static class SingletonHolder{
        static final QiniuUploadManager instance = new QiniuUploadManager();
    }

    public static QiniuUploadManager getInstance() {
        return SingletonHolder.instance;
    }

    UploadManager mUploadManager;

    QiniuUploadManager() {
        Configuration config = new Configuration.Builder()
//                .chunkSize(256 * 1024)  //分片上传时，每片的大小。 默认 256K
//                .putThreshhold(512 * 1024)  // 启用分片上传阀值。默认 512K
//                .connectTimeout(10) // 链接超时。默认 10秒
//                .responseTimeout(60) // 服务器响应超时。默认 60秒
//                .recorder(recorder)  // recorder 分片上传时，已上传片记录器。默认 null
//                .recorder(recorder, keyGen)  // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(Zone.zone0) // 设置区域，指定不同区域的上传域名、备用域名、备用IP。默认 Zone.zone0
                .build();
        mUploadManager = new UploadManager(config);
    }

    public void upload(String path, String key, String token, UpCompletionHandler handler) {
        upload(path, key, token, handler, null);
    }

    public void upload(String path, String key, String token, UpCompletionHandler handler, UpProgressHandler progressHandler) {

        mUploadManager.put(path, key, token, handler, new UploadOptions(null, null, false, progressHandler, null));
    }

    public void upload(byte[] imgDatas, String key, String token, UpCompletionHandler handler) {
        upload(imgDatas, key, token, handler, null);
    }

    public void upload(byte[] imgDatas, String key, String token, UpCompletionHandler handler, UpProgressHandler progressHandler) {

        mUploadManager.put(imgDatas, key, token, handler, new UploadOptions(null, null, false, progressHandler, null));
    }


    public interface GetTokenListener {
        void onGetToken(String token);
        void onGetTokenApiFail(String error);
        void onGetTokenNetworkFail(VolleyError volleyError);
    }

    public interface UpLoadListener extends GetTokenListener{
        void uploadSuccess(String url, int w, int h);
        void uploadFail(String error);
    }


    public void callApiGetUploadToken(final GetTokenListener getTokenListener) {

        ApiClientHelper.getApi(ApiSetting.getQiniuToken(), new TypeToken<String>() {
        }, new Response.Listener<ApiResult<String>>() {
            @Override
            public void onResponse(ApiResult<String> apiResult) {
                if (!apiResult.success) {
                    if (getTokenListener != null)
                        getTokenListener.onGetTokenApiFail(apiResult.getMsg());
                    return;
                }
                if (getTokenListener != null)
                    getTokenListener.onGetToken(apiResult.getResult());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                if (getTokenListener != null)
                    getTokenListener.onGetTokenNetworkFail(volleyError);
            }
        }, this);
    }


    public void getTokenAndUploadHeadImg(final String imgPath, final UpLoadListener upLoadListener){

        callApiGetUploadToken(new GetTokenListener() {
            @Override
            public void onGetToken(String token) {
                if (upLoadListener != null) {
                    upLoadListener.onGetToken(token);
                }


                String key = String.format("%s%s.%s", LoginManager.getUser() != null ?  LoginManager.getUser().userAppId : "", String.valueOf(System.currentTimeMillis()), "jpg");
                QiniuUploadManager.getInstance().upload(imgPath, key, token, new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo responseInfo, JSONObject jsonObject) {
//                Log.e(TAG, responseInfo.toString());
                        if (responseInfo.isOK()) {
                            String imgUrl = String.format("%s/%s", BuildConfig.QN_PHOTO, key);
                            int w = 0;
                            int h= 0;
                            try {
                                w = jsonObject.getInt("w");
                                h = jsonObject.getInt("h");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            if (upLoadListener != null) {
                                upLoadListener.uploadSuccess(imgUrl, w, h);
                            }
                        } else {
                            if (upLoadListener != null) {
                                upLoadListener.uploadFail(responseInfo.error);
                            }
                        }
                    }
                }, new UpProgressHandler() {
                    @Override
                    public void progress(String s, double v) {
                        ToastUtil.displayShortToastMsg(String.format("已上传%s％", String.valueOf((int) (v * 100))));
                    }
                });
            }

            @Override
            public void onGetTokenApiFail(String error) {
                if (upLoadListener != null)
                    upLoadListener.onGetTokenApiFail(error);
            }

            @Override
            public void onGetTokenNetworkFail(VolleyError volleyError) {
                if (upLoadListener != null)
                    upLoadListener.onGetTokenNetworkFail(volleyError);
            }
        });

    }

    public void getTokenAndUpload(final String filePath,final int resType,final UpLoadListener upLoadListener){

        callApiGetUploadToken(new GetTokenListener() {
            @Override
            public void onGetToken(String token) {
                if (upLoadListener != null) {
                    upLoadListener.onGetToken(token);
                }


                String key = getKey(resType);
                QiniuUploadManager.getInstance().upload(filePath, key, token, new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo responseInfo, JSONObject jsonObject) {
                        if (responseInfo.isOK()) {
//                            String imgUrl = String.format("%s/%s", getDomain(resType), key);

                            String mediaUrl = String.format("%s/%s", BuildConfig.QN_PHOTO, key);

                            int w = 0;
                            int h= 0;

                            if(resType == TopicListItem.LIVE_TYPE_IMG){
                                try {
                                    w = jsonObject.getInt("w");
                                    h = jsonObject.getInt("h");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            if (upLoadListener != null) {
                                upLoadListener.uploadSuccess(mediaUrl, w, h);
                            }
                        } else {
                            if (upLoadListener != null) {
                                upLoadListener.uploadFail(responseInfo.error);
                            }
                        }
                    }
                }, new UpProgressHandler() {
                    @Override
                    public void progress(String s, double v) {
                       ToastUtil.displayShortToastMsg(String.format("已上传%s％", String.valueOf((int) (v * 100))));
                    }
                });
            }

            @Override
            public void onGetTokenApiFail(String error) {
                if (upLoadListener != null)
                    upLoadListener.onGetTokenApiFail(error);
            }

            @Override
            public void onGetTokenNetworkFail(VolleyError volleyError) {
                if (upLoadListener != null)
                    upLoadListener.onGetTokenNetworkFail(volleyError);
            }
        });

    }

    private String getKey(int resType) {
        return String.format("%s%s.%s", LoginManager.getUser().userAppId, String.valueOf(System.currentTimeMillis()), resType == TopicListItem.LIVE_TYPE_IMG ? "jpg" : "wav");
    }

//    public String getDomain(int resType){
//        if (resType == ApiSetting.RES_TYPE_PHOTO){
//            return BuildConfig.QN_PHOTO; //HuabanApp.isRelease() ? DOMAIN_PHOTO_RELEASE : DOMAIN_PHOTO_DEBUG;
//        }else {//if (resType == ApiSetting.RES_TYPE_VIDEO){
//            return BuildConfig.QN_MEDIA;
//        }
////        else {
////            return DOMAIN_LIVE;
////        }
//    }
}
